<?php

namespace App;

use App\Library\Model\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use Notifiable, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'avatar',
        'code',
        'mobile',
        'name',
        'email',
        'password',
        'oauth_provider',
        'oauth_provider_id',
        'oauth_provider_token',
        'oauth_provider_expire_at',
        'remember_token',
        'revoked',
    ];

    public $rules = [
        'avatar'=>'nullable|url',
        'code'=>'required|integer',
        'mobile'=>'required|mobile',
        'name'=>'required|string|max:32|min:2',
        'email'=>'required|email',
        'password'=>'nullable|',
        'oauth_provider'=>'nullable|string',
        'oauth_provider_id'=>'nullable|string',
        'oauth_provider_token'=>'nullable|string',
        'oauth_provider_expire_at'=>'nullable|datetime',
        'remember_token'=>'nullable|string',
//        'revoked'=>'nullable|integer',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];


    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'oauth_provider_expire_at'=>'datetime',
        'revoked'=>'bool'
    ];

    /**
     * Find the user instance for the given username.
     *
     * @param  string  $username
     * @return \App\User
     */
    public function findForPassport($username)
    {
        if(is_numeric($username)){
            if (preg_match("/^1[1-9]\\d{9}$/", $username)) {
                return $this->where('mobile', $username)->first();
            } else {
                return $this->where('code', $username)->first();
            }
        } else {
            return $this->where('email', $username)->first();
        }


    }

}
